package com.mengtian_tech.tju.dataquery.api.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import tju.utils.EnvTool;
 
public class AIChatService {
	
	 public static String sendMsg(String msg) {
		 
		 msg = msg.replaceAll("\\n", "");
		
		String ai_url = "https://ds.tju.edu.cn/api/v2/chat/completions";						 
		
		if(EnvTool.isDevMode()) {
			ai_url = "http://172.31.125.13/api/v2/chat/completions";
		}
		
		OkHttpClient client = new OkHttpClient().newBuilder().build();
		
		MediaType mediaType = MediaType.parse("application/json");
		
		String bodyContent = "{"
				+ "    \"max_tokens\": 50000,"
				+ "    \"model\": \"qwen3-235b-a22b-no-think\","
				+ "    \"temperature\": 0.8,"
				+ "    \"top_p\": 1,"
				+ "    \"presence_penalty\": 1,"
				+ "    \"detail\": true,"
				+ "    \"chatId\": \"tjuchat-1748526553554-636931-264377-660629\","
				+ "    \"use_internet\": false,"
				+ "    \"messages\": ["
				+ "        {"
				+ "            \"role\": \"user\","
				+ "            \"content\": \""+msg+"\""
				+ "        }"
				+ "    ],"
				+ "    \"stream\": true,"
				+ "    \"agent\": \"churuxiao\""
				+ "}";
		
		RequestBody body = RequestBody.create(mediaType,bodyContent);
	
		
		Request request = new Request.Builder().url(ai_url).method("POST", body)
				.addHeader("Accept", "*/*" )
				.addHeader("Connection", "keep-alive" )
				.addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
				.addHeader("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJodHRwOi8vYWkudGp1LmVkdS5jbiIsImlhdCI6MTc0MjU0OTQ0MiwiZXhwIjoxNzQzMTU0MjQyLCJzdWIiOiIxMTIxMjQ0MDg0In0.z0KcLv8iMYieVV3n2GH6gvpUyH2vi25pgPIzZQH64OEse4zMMKrhFhLhjDMZB5NNuY6YsAdt0SQ2U40kdOXVyA")
				.addHeader("Host", "ds.tju.edu.cn")
				.addHeader("Content-Type", "application/json")
				.build();
		
		
		try {
			Response response = client.newCall(request).execute();
			byte[] respContent =  response.body().bytes();
			String respStr = new String(respContent,"UTF-8");
			
			
			BufferedReader reader = new BufferedReader(new StringReader(respStr));
			String str = reader.readLine();
			
			StringBuilder result = new StringBuilder();
			
			while(str != null) {
				
				if("event: answer".equals(str)) {
					//有答案，读取下一行
					str = reader.readLine();
					
					if(str != null) {
						//开始解析问题
						System.out.println(str);
						if(str.contains("[DONE]")) {
							break;
						}
						
						JSONObject json = JSON.parseObject(str.trim().substring(5).trim());
						JSONArray jsonArray = json.getJSONArray("choices");
						String content = jsonArray.getJSONObject(0).getJSONObject("delta").getString("content");
						if(content != null) {
							result.append(content);
						}
					}
					
					//最后处理后面的
					str = reader.readLine();
					
					
				}else {
					//其他情况，直接读取后面一行
					str = reader.readLine();
					continue;
				}
				
			}
			
			
			return result.toString();
			 
			
		} catch (IOException e) {
			 return null;
		}
	}
	
	
	public static void main(String args[]) {
		sendMsg("你好啊，今年有多少学生毕业？");
	}
	
}
